package com.huahua.api.repository;

import com.huahua.api.entity.pojo.CloudPrintJob;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * @author Huahua-Ai
 * @date 2025-07-24 17:52:00
 * @description 云打印任务Repository
 */
@Repository
public interface CloudPrintJobRepository extends ReactiveCrudRepository<CloudPrintJob, Long> {

    /**
     * 根据任务ID查找
     */
    Mono<CloudPrintJob> findByJobId(String jobId);

    /**
     * 根据请求ID查找
     */
    Mono<CloudPrintJob> findByRequestId(String requestId);

    /**
     * 查找设备的所有任务
     */
    Flux<CloudPrintJob> findByDeviceIdOrderBySubmittedAtDesc(String deviceId);

    /**
     * 查找设备的未完成任务
     */
    Flux<CloudPrintJob> findByDeviceIdAndJobStatusIn(String deviceId, String... statuses);

    /**
     * 根据状态查找任务
     */
    Flux<CloudPrintJob> findByJobStatus(String jobStatus);

    /**
     * 更新任务状态
     */
    @Query("UPDATE cloud_print_job SET job_status = :status, job_state_message = :message, updated_at = :updatedAt WHERE job_id = :jobId")
    Mono<Integer> updateJobStatus(String jobId, String status, String message, LocalDateTime updatedAt);

    /**
     * 更新任务进度
     */
    @Query("UPDATE cloud_print_job SET printed_pages = :printedPages, updated_at = :updatedAt WHERE job_id = :jobId")
    Mono<Integer> updatePrintProgress(String jobId, Integer printedPages, LocalDateTime updatedAt);

    /**
     * 标记任务完成
     */
    @Query("UPDATE cloud_print_job SET job_status = 'completed', completed_at = :completedAt, updated_at = :completedAt WHERE job_id = :jobId")
    Mono<Integer> markAsCompleted(String jobId, LocalDateTime completedAt);

    /**
     * 标记任务失败
     */
    @Query("UPDATE cloud_print_job SET job_status = 'failed', error_message = :error, completed_at = :completedAt, updated_at = :completedAt WHERE job_id = :jobId")
    Mono<Integer> markAsFailed(String jobId, String error, LocalDateTime completedAt);

    /**
     * 查找超时的待处理任务
     */
    Flux<CloudPrintJob> findByJobStatusAndSubmittedAtBefore(String jobStatus, LocalDateTime time);
}
